package cn.gong.jizhang.datacenter.async;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import cn.gong.jizhang.enumparams.DbTaskType;
import cn.gong.jizhang.http.HttpThreadPoolExecutor;
import cn.gong.jizhang.utils.DebugUtils;

public class AsyncData {
	private byte[] lock = new byte[0];
	private static AsyncData instance = new AsyncData();
	private ThreadPoolExecutor executor;

	private AsyncData() {
		executor = new HttpThreadPoolExecutor(5, 8, 180, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10), new ThreadPoolExecutor.DiscardOldestPolicy());
	}

	public static AsyncData getInstance() {
		return instance;
	}

	public void deal(final DbTaskType taskType, final DBCallBack callBack, final DBDeal deal) {
		executor.execute(new Runnable() {
			public void run() {
				Looper.prepare();
				synchronized (lock) {
					Handler handler = new Handler() {
						public void handleMessage(Message message) {
							try {
								if (callBack != null) {
									callBack.dbTaskFinish(taskType, message.obj);
								}
							} catch (Exception e) {
								DebugUtils.exception(e);
							}
						}
					};

					Message message = handler.obtainMessage();
					message.obj = deal.deal();
					handler.sendMessage(message);
				}
				Looper.loop();
			}
		});
	}

	public interface DBDeal {
		public Object deal();
	}

	public interface DBCallBack {
		public void dbTaskFinish(DbTaskType tasktype, Object data);
	}

}
